<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/26
 * Time: 2:03
 *
 */

namespace Admin\Controller;


use Common\Controller\CommonController;

class VideoController extends CommonController
{
    /**
     * +----------------------------------------------------------
     * 定义
     * +----------------------------------------------------------
     */
    protected $model;

    /**
     * +----------------------------------------------------------
     * 初始化
     * +----------------------------------------------------------
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model = M('Video');
    }

    public function index()
    {
        $where            = [];
        $search           = I('post.search', []);
        $pageSize         = I('post.pageSize', 20, 'intval');
        $pageCurrent      = I('post.pageCurrent', 1, 'intval');
        $pageCurrent      = max(1, $pageCurrent);
        $search['status'] = isset($search['status']) ? ($search['status'] === '' ? -1 : $search['status']) : -1;
        if (!empty($search['atime'])) {
            $where['atime'] = ['between', [strtotime($search['atime']), strtotime($search['atime'] . ' 23:59:59')]];
        }
        if (!empty($search['title'])) {
            $where['title'] = ['like', $search['title'] . '%'];
        }
        if ($search['status'] != -1) {
            $where['status'] = $search['status'];
        }
        if (!empty($search['type'])) {
            $where['type'] = $search['type'];
        }
        $count = $this->model->where($where)->count();
        $list  = $this->model->where($where)->limit((($pageCurrent - 1) * $pageSize) . ',' . $pageSize)->select();
        foreach($list as $key => $value) {
            $list[$key]['repcount'] = M('VideoReply')->where("mid = '{$value[id]}'")->count('mid');
        }
        $this->assign('search', $search);
        $this->assign('total', $count);
        $this->assign('list', $list);
        $this->display();
    }

    public function add()
    {
        if (IS_POST) {
            $data  = I('post.info');
            $dev = WEB_ROOT.$data['thumbnail'];
            if(!is_file($dev)){
                $this->ajaxReturn(['statusCode' => 300, 'message' => '视频文件不存在']);
            }
            /*F_dw*/
            if($this->model->where("title = '{$data['title']}'")->find()) {
                $this->ajaxReturn(['statusCode' => 300, 'message' => '视频标题重复！']);
            }
            $inset = [
                'title'       => $data['title'],
                'type'        => $data['cid'],
                'status'      => $data['status'],
                'keywords'    => $data['keywords'],
                'video'       => $data['thumbnail'],
                'msg'         => $data['content'],
                'description' => $data['description'],
                'summary'     => $data['summary'],
                'muid'     => 0,
                'author'     => '牛人网',
                'addrip'=>get_client_ip(),
                'atime'=>time(),
            ];
            $ref=$this->model->data($inset)->add();
            if(is_bool($ref)){
                $this->ajaxReturn(['statusCode' => 300, 'message' => '保存失败']);
            }else{
                $this->ajaxReturn(['statusCode' => 200, 'message' => '保存成功']);
            }
        } else {
            //视频大小F_dw
            $vsize[0] = M('Vsize')->where('id = 1')->getField('values');
            $vsize[1] = $vsize[0] * 1024;
            $this->assign('vsize',$vsize);
            $this->display();
        }
    }

    public function upload()
    {
        $upload           = new \Think\Upload();
        $upload->exts     = array('flv','avi','mp4','qt','mov','rmvb','mpeg');
        $upload->hash     = true;
        $upload->rootPath = WEB_ROOT;
        $upload->savePath = 'Uploads' . DIRECTORY_SEPARATOR . 'video' . DIRECTORY_SEPARATOR . 'zhibo' . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d') . DIRECTORY_SEPARATOR;
        $upload->replace  = false;
        $upload->autoSub  = true;
        $info             = $upload->uploadOne($_FILES['file']);
        if (empty($info)) {
            $this->ajaxReturn(['statusCode' => 300, 'message' => $upload->getError()]);
        }
        $file = str_replace('\\', '/', $info['savepath']) . $info['savename'];
        // todo:执行系统命令
        $url  = U($file, '', '', true);
        $this->ajaxReturn(['statusCode' => 200, 'message' => '上传成功', 'filename' => $file]);
    }

    public function info()
    {
        $id = I('get.id', 0 , 'intval');
        if(empty($id)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '无效参数']);
        }
        $info = $this->model->where(['id'=>$id])->find();
        $info['poster']='Public/Img/noThumbnail.jpg';
        if($info['thumb']==2){
            $info['poster'] = is_file(WEB_ROOT . substr($info['video'], 0, -4) . '_thumb.jpg') ? substr($info['video'], 0,
                    -4) . '_thumb.jpg' : $info['poster'];
        }
        if($info['transform']==2) {
            $info['video'] = is_file(WEB_ROOT . substr($info['video'], 0, -4) . '_new.mp4') ? substr($info['video'], 0,
                    -4) . '_new.mp4' : $info['video'];
        }
        $this->assign("info", $info);
        $this->display();
    }

    public function edit()
    {
        if(IS_POST){
            $data  = I('post.info');
            $dev = WEB_ROOT.$data['thumbnail'];
            if(!is_file($dev)){
                $this->ajaxReturn(['statusCode' => 300, 'message' => '视频文件不存在']);
            }
            
            $id = intval($data['id']);
            if(empty($id)){
                $this->ajaxReturn(['statusCode' => 300, 'message' => '无效参数']);
            }
            /*F_dw*/
            $is_have = $this->model->where("title = '{$data['title']}'")->find();
            if($is_have['id'] != $id) {
                $this->ajaxReturn(['statusCode' => 300, 'message' => '视频标题重复！']);
            }
            $inset = [
                'title'       => $data['title'],
                'type'        => $data['cid'],
                'status'      => $data['status'],
                'keywords'    => $data['keywords'],
                'video'       => $data['thumbnail'],
                'msg'         => $data['content'],
                'description' => $data['description'],
                'summary'     => $data['summary'],
            ];
            $info = $this->model->where(['id'=>$id])->find();
            if($info['video']!=$data['thumbnail']){
                $inset['transform']=$inset['thumb']=0;
            }
            
            $ref=$this->model->where(['id'=>$id])->data($inset)->save();
            if(is_bool($ref)){
                $this->ajaxReturn(['statusCode' => 300, 'message' => '操作失败']);
            }else{
                $this->ajaxReturn(['statusCode' => 200, 'message' => '操作成功', 'closeCurrent' => true]);
            }
        }else{
            $id = I('get.id', 0 , 'intval');
            if(empty($id)){
                $this->ajaxReturn(['statusCode' => 300, 'message' => '无效参数']);
            }
            $info = $this->model->where(['id'=>$id])->find();

            //视频大小F_dw
            $vsize[0] = M('Vsize')->where('id = 1')->getField('values');
            $vsize[1] = $vsize[0] * 1024;
            $this->assign('vsize',$vsize);
            
            $this->assign('info', $info);
            $this->display('add');
        }
    }

    /**
     * 删除视频
     */
    public function del()
    {
        $id = I('get.id','0','intval');
        $ids = I('get.ids','0','trim');
        $ids = empty($id)?$ids:$id;
        if(empty($ids)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '无效参数']);
        }
        $ids = explode(',',$ids);
        $reds = $this->model->field(['id','video'])->where(['id'=>['in',$ids]])->select();
        $del = $this->model->where(['id'=>['in',$ids]])->delete();
        if($del){
            foreach($reds as $v){
                $dev = WEB_ROOT.$v['video'];
                if(is_file($dev)){
                    unlink($dev);
                }
                if(is_file(substr($dev, 0, -4).'_new.mp4')){
                    unlink(substr($dev, 0, -4).'_new.mp4');
                }
                if(is_file(substr($dev, 0, -4).'_thumb.jpg')){
                    unlink(substr($dev, 0, -4).'_thumb.jpg');
                }
            }
            // 删除评论
            M('VideoReply')->where(['mid'=>['in',$ids]])->delete();
            $this->ajaxReturn(['statusCode' => 200, 'message' => '删除成功']);
        }else{
            $this->ajaxReturn(['statusCode' => 300, 'message' => '删除失败']);
        }
    }

    /**
     * 视频转换
     */
    public function change()
    {
        $id = I('get.id', 0 , 'intval');
        if(empty($id)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '无效参数']);
        }
        $dev = $this->model->getFieldById($id,'video');

        if(empty($dev)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '无视频资源']);
        }
        $dev = WEB_ROOT.$dev;
        if(!is_file($dev)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '视频['.$id.']原始内容丢失']);
        }

        $new_file = substr($dev, 0, -4).'_new.mp4';
        // 检查是否在转换中
        $runshell = 'ps -ef | grep '.$new_file.' | grep -v grep | wc -l';
        $cmd  = popen($runshell,'r');
        $line = (int)fread($cmd, 512);
        pclose($cmd);
        if(!empty($line)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '视频['.$id.']转换中']);
        }
        if(is_file($new_file)){
            $this->model->where(['id'=>$id])->setField('transform',2);
            $this->ajaxReturn(['statusCode' => 200, 'message' => '已经成功转换']);
        }
        $cmd  = popen($runshell,'r');
        $line = (int)fread($cmd, 512);
        pclose($cmd);
        if(!empty($line)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '视频['.$id.']转换中']);
        }
        // 视频转换
        $this->model->where(['id'=>$id])->setField('transform',1);
        $shell = '/usr/local/bin/ffmpeg -i '.$dev.' -vcodec mpeg4 -bf 0 -g 20 -s 720*480 -b:v 1024 -f mp4 -y '.$new_file;
        $cmd = popen($shell." >/dev/null 2>&1 &",'r');
        pclose($cmd);
        $this->ajaxReturn(['statusCode' => 200, 'message' => '视频['.$id.']转换成功执行']);
    }

    /**
     * 设置视频截图
     */
    public function printscreen()
    {
        $id = I('get.id', 0 , 'intval');
        $time = I('get.time',1,'intval');
        $time = max(1,$time);
        if(empty($id)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '无效参数']);
        }
        $dev = $this->model->getFieldById($id,'video');

        if(empty($dev)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '无视频资源']);
        }
        $dev = WEB_ROOT.$dev;
        if(!is_file($dev)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '视频['.$id.']原始内容丢失']);
        }

        $new_file = substr($dev, 0, -4).'_thumb.jpg';
        $runshell = 'ps -ef | grep '.$new_file.' | grep -v grep | wc -l';
        $cmd  = popen($runshell,'r');
        $line = (int)fread($cmd, 512);
        pclose($cmd);
        if(!empty($line)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '视频['.$id.']截图执行中']);
        }
        if(is_file($new_file)){
            $this->model->where(['id'=>$id])->setField('thumb',2);
            $this->ajaxReturn(['statusCode' => 200, 'message' => '视频['.$id.']截图执行成功']);
        }
        $cmd  = popen($runshell,'r');
        $line = (int)fread($cmd, 512);
        pclose($cmd);
        if(!empty($line)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '视频['.$id.']截图执行中']);
        }
        $this->model->where(['id'=>$id])->setField('thumb',1);
        $shell='ffmpeg -i ' . $dev . ' -y -f  image2 -s 720*480 -ss ' . $time . ' -vframes 1  ' . $new_file.'  >/dev/null 2>&1 &';
        $cmd = popen($shell,'r');
        pclose($cmd);
        $this->ajaxReturn(['statusCode' => 200, 'message' => '视频['.$id.']截图成功执行']);
    }

    public function checkArticleTitle()
    {
        $where = "title='" . $_GET['title'] . "'";
        if (!empty($_GET['id'])) {
            $where .= " And id !=" . (int)$_GET['id'];
        }
        if ($this->model->where($where)->count() > 0) {
            $this->ajaxReturn(array('statusCode' => 300, 'message' => "已经存在，请修改标题"));
        } else {
            $this->ajaxReturn(array('statusCode' => 200, 'message' => "可以使用"));
        }
    }

    /**
     * 回复列表
     */
    public function replist(){
        $where=[];
        $search=[];
        $search['mid']=I('get.id',0,'intval');
        $search['rtime']=I('get.rtime','','trim');
        $search['content']=I('get.content','','trim');
        $search['mnickname']=I('get.mnickname','','trim');
        $pageSize         = I('post.pageSize', 20, 'intval');
        $pageCurrent      = I('post.pageCurrent', 1, 'intval');
        $pageCurrent      = max(1, $pageCurrent);
        if(!empty($search['mid'])){
            $where['mid']=$search['mid'];
        }
        if(!empty($search['rtime'])){
            $where['rtime']=['between', [strtotime($search['rtime']), strtotime($search['rtime'] . ' 23:59:59')]];;
        }
        if (!empty($search['content'])) {
            $where['content'] = ['like', '%' . trim($search['content']) . '%'];
        }
        if (!empty($search['mnickname'])) {
            $where['m.nickname'] = ['like', '%' . trim($search['mnickname']) . '%'];
        }
        $dbrep=M('VideoReply');
        $count = $dbrep->alias("v_r")->join("left join ".C("DB_PREFIX")."member m on m.muid = v_r.muid")->join("left join ".C("DB_PREFIX")."video v on v.id = v_r.mid")->where($where)->count();
        $list  = $dbrep->alias("v_r")->join("left join ".C("DB_PREFIX")."member m on m.muid = v_r.muid")->join("left join ".C("DB_PREFIX")."video v on v.id = v_r.mid")->where($where)->field("v_r.*,m.nickname as mnickname,v.title as vtitle")->order('rtime desc')->limit((($pageCurrent - 1) * $pageSize) . ',' . $pageSize)->select();
        $this->assign('search', $search);
        $this->assign('total', $count);
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * 评论删除
     */
    public function rdel(){
        $id = I('get.id','0','trim');
        $ids = I('get.ids','0','trim');
        $ids = empty($id)?$ids:$id;
        if(empty($ids)){
            $this->ajaxReturn(['statusCode' => 300, 'message' => '无效参数']);
        }
        $ids = explode(',',$ids);
        $dbrep=M('VideoReply');
        $del = $dbrep->where(['rid'=>['in',$ids]])->delete();
        if($del){
            $this->ajaxReturn(['statusCode' => 200, 'message' => '处理成功']);
        }else{
            $this->ajaxReturn(['statusCode' => 300, 'message' => '处理失败']);
        }
    }

    /**
     * 视频上传大小F_dw
     */
    public function uploadsize() {
        if(IS_POST) {
            $id = I('post.id');
            $values = I('post.values');
            $res = M('Vsize')->where("id = '{$id}'")->setField('values',$values);
            if($res) {
                $this->ajaxReturn(['statusCode' => 200, 'message' => '处理成功']);
            }else{
                $this->ajaxReturn(['statusCode' => 300, 'message' => '处理失败']);
            }
        } else {
            $info = M('Vsize')->where('id = 1')->find();

            $this->assign('info',$info);
            $this->display();
        }
    }
}
